package comoabejas

import groovy.transform.Synchronized;
import org.hibernate.Query
import org.springframework.core.io.ClassPathResource
import org.springframework.core.io.Resource
import java.net.URL

class DealService {
	def areaService
	def clientService
	def purchaseService
	def emailService
	def userService
	def imageService
	
	
    static transactional = true

    def serviceMethod() {

    }
    public Deal saveObj(Deal deal){
		
		Calendar cal = Calendar.getInstance()
		
		cal.setTime(deal.getStartDate())
		cal.clear(Calendar.HOUR_OF_DAY)
		cal.clear(Calendar.MILLISECOND)
		//cal.clear(Calendar.MINUTE)

		deal.setStartDate(cal.getTime())
		
		cal.setTime(deal.getEndDate())
		cal.clear(Calendar.HOUR_OF_DAY)
		cal.clear(Calendar.MILLISECOND)
		cal.clear(Calendar.MINUTE)

		deal.setEndDate(cal.getTime())

		/*
		List lista = Deal.findAllByStartDate( deal.getStartDate(), deal.getEndDate() )
		
		if(!lista.isEmpty()){
			throw new RuntimeException("ya existe un deal en esa fecha")
		}
		*/
				
    	if(deal.getCurrentNumberOfUsers()==null){
    		deal.setCurrentNumberOfUsers(0);
    	}
    	try{
    		if(deal.save(flush:true)){
    			return deal;
    		}
    		
    	}catch (Exception e) {
			e.printStackTrace()
		}
    }
    
    def listObj(){
       def g = [dealInstanceList: Deal.list(), dealInstanceTotal: Deal.count()]
       return g;
    }
    public Deal getObj(Long id){
        def dealInstance = Deal.get(id)
        return dealInstance
    }
    public void deleteObj(Deal obj){
        obj.delete(flush: true)

    }
	def listDealsByState(String state){
		//def a = Deal.findByState(state, [sort:'endDate',order:'desc'])
		
		/*
		def safeMax = Math.min(params.max?.toInteger(), 100) // never let more than 100 results be returned
		return SomeClass.list(max:safeMax)
		*/
		
		def results = Deal.findAll("from Deal as b where b.state = :state order by b.endDate desc",[state:state])
		return results;
	}
    def generateData = {
    		def lista = Deal.list()
    		
			for (int i = 0; i < lista.size; ) {
				def unDeal = lista.remove(0);
				//Client.lock(cli.id)
				this.deleteObj(unDeal)
			}
    		
    		
        	areaService.generateData()
        	clientService.generateData()
        
        	def client = Client.list().get(0)
        	def area = Area.list().get(0)
        	
        	def deal = new Deal()
        	
        	deal.setAddress("adress 1")
        	deal.setArea(area)
        	deal.setClient(client)
        	deal.setConditions("conditions 123")
        	deal.setCurrentNumberOfUsers(0)
        	deal.setDescription("description 1")
        	deal.setDetails("details 1")
        	deal.setDiscountPrice(20)
        	deal.setNormalPrice(50)
        	
        	try {
				
        		deal.save(flush:true)
			} catch (Exception e) {
				e.printStackTrace()
			}
        	
        }
	
	
    public void controlarFechaDeal() {
    	
    	// compute max mod date
    	Calendar cal = Calendar.getInstance();
    	//cal.clear(Calendar.HOUR_OF_DAY)
		//cal.clear(Calendar.HOUR)
    	cal.clear(Calendar.MILLISECOND)
		cal.clear(Calendar.SECOND)
    	//cal.clear(Calendar.MINUTE)
    	
		cal.set(Calendar.YEAR,2011)
		cal.set(Calendar.MONTH,2)
		cal.set(Calendar.DAY_OF_MONTH,23)
		
		//cal.set(Calendar.MINUTE,2)
		cal.set(Calendar.HOUR_OF_DAY,0)
		
    	Date maxModDate = cal.getTime();
    	
    	// query database
		def deals = Deal.findAll("from Deal as d where d.startDate >= ? order by d.endDate asc", [maxModDate])
		//def dealList = Deal.findAllByState("ACTIVE", [sort:"dateOfCreation",order:"desc"]);
    	//def deal = Deal.find("from Deal as d where d.state = 'Active'")
		def deal = Deal.findByState("ACTIVE");
		if(deal==null){
			throw new RuntimeException("no hay un deal con estado Active")		
		}
		if(deals==null){
			throw new RuntimeException("no hay un deal con esa determinada fecha")
		}
		
		deal.setState(DealState.FINNISHED)
		def d = deals.get(0)
		d.setState(DealState.ACTIVE)
		saveObj(deal)
		saveObj(d)
				
    	
    }
    
	@Synchronized
	public Purchase comprar(Deal deal, User u){
    	Purchase purchase
		if (deal) {
			//aca hay que ver cuanto quiere comprar el cliente
			deal.setCurrentNumberOfUsers(deal.getCurrentNumberOfUsers()+1)
			try{
				
				purchase = new Purchase()
				
				//TODO en purchase service tendria que ir la conexion con dinero mail
				
					
				//si se llego al numero 
				if ((deal.currentNumberOfUsers >= deal.requiredNumberOfUsers)&&(deal.state == DealState.ACTIVE)){
					
					deal.state = DealState.READY
					emailService.sendToAllUsersPurchaseConfirmation(deal)
					
				}else if((deal.currentNumberOfUsers < deal.requiredNumberOfUsers)&&(deal.state != DealState.ACTIVE)){
				// no se puede comprar un deal que no este activo , esto es un error
					throw new RuntimeException();
				}	
				Deal d1 =saveObj(deal)
				
				purchase.setDeal(d1)
				purchase.setUser(u)
				purchase.setQuantity 1
				purchase = purchaseService.saveObj(purchase)

				emailService.sendToUserPurchaseConfirmation(u)
				
				return purchase
				
			}catch(org.springframework.mail.MailSendException e){
					e.printStackTrace();
			}catch (Exception e) {
				System.out.println(e.printStackTrace())
			}
		}
    }
	
	
	/*
	*/
	public Deal crearUnDealCompletoTest() {

		Area area = new Area()
		User user1 = new User()
		User user2 = new User()
		User user3 = new User()
		
		Client client = new Client()
		
		area.setName("Lanus")
		area.setDescription ""
		area.setType ""
		
		Area area1 = areaService.saveObj(area)
		
		
		user1.setEmail "matiaskochman@yahoo.com.ar"
		user1.setName "Matias"
		user1.setPassword "matias1"
		user1.setUsername "matias1"
		user1.setSurname "Kochman"

		user2.setEmail "matiaskochman@google.com"
		user2.setName "Matias"
		user2.setPassword "matias2"
		user2.setUsername "matias2"
		user2.setSurname "Kochman"

		user3.setEmail "matiaskochman1@google.com"
		user3.setName "Matias"
		user3.setPassword "matias3"
		user3.setUsername "matias3"
		user3.setSurname "Kochman"

		userService.saveObj(user1)
		userService.saveObj(user2)
		userService.saveObj(user3)
		
		client.setCompanyName "Kotex"
		client.setLocalidad "Lanus"
		client.setEmail1 "kotex@casdf.com"
		client.setAddress1 ""
		client.setContactName1 ""
		client.setCodigoPostal ""
		client.setContactPhone1 ""
		
		
		clientService.saveObj(client)
		
		
		def file = new File('web-app/images/tropa.jpg')
		
		assert file.exists()
		
		Imagen image = new Imagen()
		image.setMyFile(file.getBytes())
		
		imageService.saveObj(image)
		
		Calendar cal = Calendar.getInstance();
		
		createDeal2(area1, client, cal, "web-app/images/image001.jpg","23-02-2011:00:00:00",DealState.ACTIVE)
		createDeal2(area1, client, cal, "web-app/images/image002.jpg","23-02-2011:00:01:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image003.jpg","23-02-2011:00:02:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image004.jpg","23-02-2011:00:03:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image005.jpg","23-02-2011:00:04:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image006.jpg","23-02-2011:00:05:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image007.jpg","23-02-2011:00:06:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image008.jpg","23-02-2011:00:07:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image009.jpg","23-02-2011:00:08:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image010.jpg","23-02-2011:00:09:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image011.jpg","23-02-2011:00:10:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image012.jpg","23-02-2011:00:11:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image013.jpg","23-02-2011:00:12:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image014.jpg","23-02-2011:00:13:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image015.jpg","23-02-2011:00:14:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image001.jpg","23-02-2011:00:15:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image002.jpg","23-02-2011:00:16:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image003.jpg","23-02-2011:00:17:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image004.jpg","23-02-2011:00:18:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image005.jpg","23-02-2011:00:19:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image006.jpg","23-02-2011:00:20:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image007.jpg","23-02-2011:00:21:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image008.jpg","23-02-2011:00:22:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image009.jpg","23-02-2011:00:23:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image010.jpg","23-02-2011:00:24:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image011.jpg","23-02-2011:00:25:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image012.jpg","23-02-2011:00:26:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image013.jpg","23-02-2011:00:27:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image014.jpg","23-02-2011:00:28:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image015.jpg","23-02-2011:00:29:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image001.jpg","23-02-2011:00:30:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image002.jpg","23-02-2011:00:31:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image003.jpg","23-02-2011:00:32:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image004.jpg","23-02-2011:00:33:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image005.jpg","23-02-2011:00:34:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image006.jpg","23-02-2011:00:35:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image007.jpg","23-02-2011:00:36:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image008.jpg","23-02-2011:00:37:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image009.jpg","23-02-2011:00:38:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image010.jpg","23-02-2011:00:39:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image011.jpg","23-02-2011:00:40:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image012.jpg","23-02-2011:00:41:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image013.jpg","23-02-2011:00:42:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image014.jpg","23-02-2011:00:43:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image015.jpg","23-02-2011:00:44:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image001.jpg","23-02-2011:00:45:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image002.jpg","23-02-2011:00:46:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image003.jpg","23-02-2011:00:47:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image004.jpg","23-02-2011:00:48:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image005.jpg","23-02-2011:00:49:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image006.jpg","23-02-2011:00:50:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image007.jpg","23-02-2011:00:51:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image008.jpg","23-02-2011:00:52:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image009.jpg","23-02-2011:00:53:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image010.jpg","23-02-2011:00:54:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image011.jpg","23-02-2011:00:55:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image012.jpg","23-02-2011:00:56:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image013.jpg","23-02-2011:00:57:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image014.jpg","23-02-2011:00:58:00",DealState.CREATED)
		createDeal2(area1, client, cal, "web-app/images/image015.jpg","23-02-2011:00:59:00",DealState.CREATED)

				
		def dealList = Deal.findAllByState("ACTIVE", [sort:"dateOfCreation",order:"desc"]);
		
		if(dealList ==null){
			throw new RuntimeException("no encontro un deal en estado active");
		}
		
		//return deal

	}	
	private Deal createDeal(Area area, Client c, Calendar cal, Imagen image,String startDate) {
		Deal deal = new Deal()
		
		String day = startDate.substring(0,2)
		String month = startDate.substring(3,5)
		String year = startDate.substring(6,10)
		String hour = startDate.substring(11,13)
		String min = startDate.substring(14,16)

		if(day.startsWith("0")){
			day = day.substring(1)
		}
		if(month.startsWith("0")){
			month = month.substring(1)
		}

		if(min.startsWith("0")){
			min = min.substring(1)
		}
		if(hour.startsWith("0")){
			hour = hour.substring(1)
		}
		
		cal.set(Calendar.DAY_OF_MONTH, new Integer(day))
		cal.set(Calendar.MONTH, new Integer(month))
		cal.set(Calendar.YEAR, new Integer(year))
		cal.set(Calendar.HOUR_OF_DAY, new Integer(hour))
		cal.set(Calendar.MINUTE, new Integer(min))
		
		cal.clear(Calendar.SECOND)
		//cal.clear(Calendar.HOUR_OF_DAY)
		cal.clear(Calendar.MILLISECOND)
		//cal.clear(Calendar.MINUTE)
		
		deal.setAddress "sarlanga"
		deal.setTitle("test integracion")
		deal.setConditions ""
		deal.setDescription ""
		deal.setDetails ""

		deal.setArea(area)
		deal.setClient(c)
		deal.setStartDate(cal.getTime())

		cal.add(Calendar.DAY_OF_MONTH, 1)

		deal.setEndDate(cal.getTime())

		cal.add(Calendar.DAY_OF_MONTH, 1)

		deal.setVoucherStartDate(cal.getTime())
		cal.add(Calendar.DAY_OF_MONTH, 1)

		deal.setVoucherEndDate(cal.getTime())

		deal.setDiscountPrice(20f)
		deal.setNormalPrice(100f)
		deal.setRequiredNumberOfUsers(5)
		deal.setCurrentNumberOfUsers(0)
		deal.setState(DealState.ACTIVE)
		deal.setImage(image)
		deal.setDateOfCreation(new Date())


		Deal deal1 = saveObj(deal)
		return deal1
	}
	
	private Deal createDeal2(Area area, Client c, Calendar cal, String imagePath,String startDate,String state) {
		
		
		def file = new File(imagePath)
		
		assert file.exists()
		
		Imagen img = new Imagen()
		img.setMyFile(file.getBytes())
		
		Imagen image = imageService.saveObj(img)
		
		Deal deal = new Deal()
		
		String day = startDate.substring(0,2)
		String month = startDate.substring(3,5)
		String year = startDate.substring(6,10)
		String hour = startDate.substring(11,13)
		String min = startDate.substring(14,16)

		if(day.startsWith("0")){
			day = day.substring(1)
		}
		if(month.startsWith("0")){
			month = month.substring(1)
		}

		if(min.startsWith("0")){
			min = min.substring(1)
		}
		if(hour.startsWith("0")){
			hour = hour.substring(1)
		}
		
		cal.set(Calendar.DAY_OF_MONTH, new Integer(day))
		cal.set(Calendar.MONTH, new Integer(month))
		cal.set(Calendar.YEAR, new Integer(year))
		cal.set(Calendar.HOUR_OF_DAY, new Integer(hour))
		cal.set(Calendar.MINUTE, new Integer(min))
		
		cal.clear(Calendar.SECOND)
		//cal.clear(Calendar.HOUR_OF_DAY)
		cal.clear(Calendar.MILLISECOND)
		//cal.clear(Calendar.MINUTE)
		
		deal.setAddress "sarlanga"
		deal.setTitle("test integracion")
		deal.setConditions ""
		deal.setDescription ""
		deal.setDetails ""

		deal.setArea(area)
		deal.setClient(c)
		deal.setStartDate(cal.getTime())

		cal.add(Calendar.DAY_OF_MONTH, 1)

		deal.setEndDate(cal.getTime())

		cal.add(Calendar.DAY_OF_MONTH, 1)

		deal.setVoucherStartDate(cal.getTime())
		cal.add(Calendar.DAY_OF_MONTH, 1)

		deal.setVoucherEndDate(cal.getTime())

		deal.setDiscountPrice(20f)
		deal.setNormalPrice(100f)
		deal.setRequiredNumberOfUsers(5)
		deal.setCurrentNumberOfUsers(0)
		deal.setState(state)
		deal.setImage(image)
		deal.setDateOfCreation(new Date())


		Deal deal1 = saveObj(deal)
		return deal1
	}

}
